import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth.js'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      redirect: '/home',
      component: () => import('../views/index.vue'),
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('../views/home/index.vue'),
        },
        {
          path: '/brand',
          name: 'brand',
          component: () => import('../views/brand/index.vue'),
        },
        {
          path: '/culture',
          name: 'culture',
          component: () => import('../views/culture/index.vue'),
        },
        {
          path: '/flow',
          name: 'flow',
          component: () => import('../views/flow/index.vue'),
        },
        {
          path: '/plant',
          name: 'plant',
          component: () => import('../views/plant/index.vue'),
        },
        {
          path: '/process',
          name: 'process',
          component: () => import('../views/process/index.vue'),
        },
        {
          path: '/service',
          name: 'service',
          component: () => import('../views/service/index.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = getToken()
  // 判断是否需要登录权限
  if (to.fullPath != '/login') {
    if (!token) {
      ElMessage.error('请先登录')
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
